import React, {useEffect, useRef, useState} from 'react';
import UserForm from "../../../components/user-manage/UserForm";
import axios from "axios";
import {Button, Table, Modal, Switch} from "antd";
import {DeleteOutlined, EditOutlined,ExclamationCircleOutlined} from "@ant-design/icons";

const {confirm} = Modal

const UserList = () => {

    const [dataSource,setDataSource]=useState([])
    const [isVisible,setIsVisible]=useState(false)
    const [regionList,setRegionList]=useState([])
    const [roleList,setRoleList]=useState([])
    const [current,setCurrent]=useState([])
    const addForm = useRef(null)
    const updateForm = useRef(null)
    const [isUpdateVisible,setIsUpdateVisible]=useState(false)
    const [isUpdateDisabled,setIsUpdateDisabled]=useState(false)

    const {roleId,username,region} = JSON.parse(localStorage.getItem('token'))
    useEffect(()=>{
        axios.get('/users?_expand=role').then(res=>{
            const list = res.data
            setDataSource(roleId===1?list:[
                ...list.filter(item=>item.username===username),
                ...list.filter(item=>item.region===region && item.roleId===3)
            ])
        })
    },[region,roleId,username])

    useEffect(()=>{
        axios.get('/regions').then(res=>{
            setRegionList(res.data)
        })
    },[])

    useEffect(()=>{
        axios.get('/roles').then(res=>{
            const list = res.data
            setRoleList(list)
        })
    },[])

    const columns = [
        {
            title:'区域',
            dataIndex:'region',
            render:(region)=>{
                return <b>{region===''?'全球':region}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render:(role)=>{
                return role.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'username',
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render:(roleState,item)=>{
                return <Switch checked={roleState} disabled={item.default} onChange={()=>switchMethod(item)}></Switch>
            }
        },
        {
            title: '操作',
            render:(item)=>{
                return <div>
                    <Button shape='circle' type={"primary"} icon={<EditOutlined/>} disabled={item.default}
                    onClick={()=>handleUpdate(item)} style={{marginRight:'5px'}}/>
                    <Button shape="circle" danger icon={<DeleteOutlined/>}
                            onClick={()=>{confirmDel(item)}} disabled={item.default}/>
                </div>
            }
        }
    ]

    function confirmDel(item) {
        confirm({
            title: '确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                deleteMethod(item);
            },
            onCancel() {
                console.log('取消');
            },
        });
    }

    const switchMethod =(item)=>{
        item.roleState=!item.roleState;
        setDataSource([...dataSource])

        axios.patch(`/users/${item.id}`,{
            roleState:item.roleState
        })
    }

    const deleteMethod = (item) =>{
        setDataSource(dataSource.filter(data=>data.id!==item.id))

        axios.delete(`/users/${item.id}`)
    }

    const handleOk=()=>{
        addForm.current.validateFields().then(value=>{
            setIsVisible(false)
            addForm.current.resetFields()

            axios.post('/users',{
                ...value,
                'roleState':true,
                'default':false
            }).then(res=>{
                setDataSource([...dataSource,{
                    ...res.data,
                    role:roleList.filter(item=>item.id===value.roleId)[0]
                }])
            })
        })
    }

    const handleCancel=()=>{
        setIsVisible(false)
    }

    const handleUpdate=(item)=>{
        setTimeout(()=>{
            setIsUpdateVisible(true)
            if(item.roleId===1){
                setIsUpdateDisabled(true)
            }else {
                setIsUpdateDisabled(false)
            }
            updateForm.current.setFieldsValue(item)
        },0)
        setCurrent(item)
    }

    const updateOk=()=>{
        updateForm.current.validateFields().then(value=>{
            setIsUpdateVisible(false)

            setDataSource(dataSource.map(item=>{
                if(item.id===current.id){
                    return{
                        ...item,
                        ...value,
                        role:roleList.filter(data=>data.id===value.roleId)[0]
                    }
                }
                return item
            }))
            setIsUpdateDisabled(!isUpdateDisabled)

            axios.patch(`/users/${current.id}`,value)
        })
    }

    return (
        <div>
            <Button type="primary" onClick={()=>setIsVisible(true)}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} pagination={{pageSize:10}} rowKey={item=>item.id}/>
            <Modal title="添加用户" visible={isVisible} onOk={handleOk} onCancel={handleCancel} cancelText={'取消'} okText={'确定'}>
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}/>
            </Modal>
            <Modal title="编辑用户" visible={isUpdateVisible} onOk={updateOk} onCancel={()=>{
                setIsUpdateVisible(false)
                setIsUpdateDisabled(!isUpdateDisabled)
            }} cancelText={'取消'} okText={'更新'}>
                <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}/>
            </Modal>
        </div>
    );
};

export default UserList;